from Initializer import Initializer
from openai import OpenAI
import os
from Search import Search

Initializer.init()

class Chat:
    def __init__(self):
        self.client = OpenAI(
            api_key=os.environ.get("APIKEY"),
            base_url=os.environ.get("BASEURL"),
        )
        self.search = Search()
        self.context = []
        
    def setBackGround(self, backGround: str):
        self.context.append({"role": "system", "content": backGround})
        
    def chat(self, text: str) -> str:
        self.context.append({"role": "user", "content": text})
        self.context.append({"role": "system", "content": f"从这个游戏的本地知识库中，你了解到：{self.search.search(text)}"})
        stream = self.client.chat.completions.create(
            model=os.environ.get("CHATMODELID"),
            messages=self.context,
            stream=True,
        )
        print(">>> ", end="")
        temp = []
        for chunk in stream:
            if not chunk.choices:
                continue
            temp.append(chunk.choices[0].delta.content)
            print(chunk.choices[0].delta.content, end="")
        print()
        self.context.append({"role": "assistant", "content": "".join(temp)})